# -*- coding: utf-8 -*-
# filename: handle.py
from urllib import unquote

import web
import qrcode
from HTMLParser import HTMLParser

gPage = '''
<html>
<head>
<title>QRCode</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
</head>
<body>
<form action="/" method="post" target="postTo" name="paraform">
二维码数据：<input type="text" name="data" autofocus="autofocus" required="required" value="在此输入"/>
</br></br>
信息容量：<input type="number" name="version" min="0" max="40" step ="1" value="0"/>（默认0为自适应）
</br>
纠错范围：
<select name="ec">
<option value="{}">7%以下的错误会被纠正</option>
<option value="{}" selected="selected">15%以下的错误会被纠正</option>
<option value="{}">25%以下的错误会被纠正</option>
<option value="{}">30%以下的错误会被纠正</option>
<select>
</br>
单点像素：<input type="number" name="boxsize" min="10" max="100" step ="1" value="10"/>
</br>
描边大小：<input type="number" name="border" min="4" max="40" step ="1" value="4"/>
</br></br>
<button type="submit" value="Submit">Submit</button>
<button type="reset" value="Reset">Reset</button>
</form>
<iframe name="postTo" frameborder="0" width="50%" height="50%"></iframe>
</body>
</html>
'''.format(qrcode.constants.ERROR_CORRECT_L,
           qrcode.constants.ERROR_CORRECT_M,
           qrcode.constants.ERROR_CORRECT_Q,
           qrcode.constants.ERROR_CORRECT_H)
gImgPath = r'./py_qrcode.png'

class Handle(object):

    global gPage
    global gImgPath

    def GET(self):
        # print '<Handle>get'
        return gPage

    def POST(self):
        # print '<Handle>post'
        webData = web.input()
        # print webData
        if webData:
            data = webData.get('data')
            if data.strip():
                data = HTMLParser().unescape(data)
                version = webData.get('version')
                if not version.strip() or version=='0': # version为None或者0
                    version = None
                else:
                    version = int(version)
                ec = int(webData.get('ec'))
                boxsize = int(webData.get('boxsize'))
                border = int(webData.get('border'))
                # print data, version, ec, boxsize, border

                qr = qrcode.QRCode(
                    version=version,
                    error_correction=ec,
                    box_size=boxsize,
                    border=border,
                )
                qr.add_data(data)
                qr.make(fit=True)
                img = qr.make_image()
                img.save(gImgPath)
                imgHtml = '<html><img src=\'{}\' alt=\'py_qrcode\' width=\'300px\'/></html>'\
                    .format(gImgPath)
                return imgHtml
        # return gPage
